Nginx的負載平衡

睡睡唸

雖然知道nginx應該可以做到負載平衡,
但從來沒弄過,
查了一下,還挺簡單的。

正文

主要有四種模式,
都是寫在upstream底下

ref. Nginx負載平衡的4種方式 :輪詢-Round Robin 、Ip地址-ip_hash、最少連接-least_conn、加權-weight=n

config.conf

upstream yolox-brand {
    least_conn;
    server yolox-brand-1:8080;
    server yolox-brand-2:8080;
}

server {
    listen       80;
    server_name  192.168.1.79;

    location / {
        proxy_pass         http://yolox-brand;
        proxy_redirect     off;
        proxy_set_header   Host $host;
        proxy_set_header   X-Real-IP $remote_addr;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Host $server_name;
        
        proxy_hide_header  'Access-Control-Allow-Origin';
        add_header Access-Control-Allow-Origin *;
        add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
        add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';

        if ($request_method = 'OPTIONS') {
            return 204;
        }
    }
}

然後,docker-compose.yaml如下,
要注意別把config檔塞錯地方了,不然會碰到 99. nginx的除錯筆記的錯誤

version: '3.8'
services:
  python-1:
    container_name: yolox-brand-1
    image: busybox
    pull_policy: if_not_present
    restart: always
    networks:
      - internal
  python-2:
    container_name: yolox-brand-2
    image: busybox
    pull_policy: if_not_present
    restart: always
    networks:
      - internal
  nginx-lb:
    container_name: nginx
    image: nginx
    pull_policy: if_not_present
    restart: always
    volumes:
      - ./proxy.conf:/etc/nginx/conf.d/proxy.conf
    ports:
      - 80:80
    networks:
      - internal
networks:
  internal:
    name: internal
    driver: bridge

補充,proxy_pass url 中包含路徑時,結尾的 / 最好同 location 匹配規則一致。

ref. proxy_pass url 反向代理的坑